#library('BubbleEventCreator');
#import('dart:html');
#import('BubbleGrid.dart');
#import('Colors.dart');
#import('BubbleUserAction.dart');
#import('BubbleDrawer.dart');

/** Class which adds onClick events to the game */
class BubbleEventCreator {

  // The class which is set to act when bubbles are clicked on.
  BubbleUserAction action;
  
  // Constructor
  BubbleEventCreator(BubbleUserAction this.action);
  
  // Clicking on the new game button resets the grid.
  void setNewGameButtonOnClickEvent() {
    Element newGameButton = document.query('#newGame');
    newGameButton.on.click.add((event) {
      action.selected = [];
      action.drawer.grid.initializeBubbles();
      action.drawer.grid.totalPoints = 0;
      action.drawer.drawGame();
    });
  }

  // Clicking on a group of same color bubbles on the grid selects/removes the group.  
  void setBubblesOnClickEvents() {
    Element gameBoard = document.query('#game');
    gameBoard.on.click.add((event) {
      String targetId = event.target.id;
      String bubblePrefix = 'bubbles[';

      // Check if a bubble was clicked on.
      if (targetId.startsWith(bubblePrefix)) {
        
        //Get its image source.
        String selectedBubbleIndex = targetId.split(bubblePrefix)[1].split(']')[0];
        String imageSrc = action.drawer.getBubbleImage(Math.parseInt(selectedBubbleIndex)).src;
        
        // If it's not an empty white box, call the clickBubble method in the BubbleUserAction,
        // with the clicked bubble's index.
        if (!imageSrc.endsWith(Colors.getSrc(null))) {
          action.clickBubble(Math.parseInt(selectedBubbleIndex));
        }
      }
    });
  }
}
